﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using org.apache.zookeeper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class OZ_ProductInfoStocksInterfaceBusiness : OZInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption OZ_Query;
        public OZ_ProductInfoStocksInterfaceBusiness()
        {
            this.InterfaceName = "商品数量信息_店铺1";
            //索引字段
            this.MapFields = GetMapField("OZ_Query");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            OZ_Query = this.interfaceOption.Where(x => x.OperateType == "OZ_Query").First();

            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求中的事件
            this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="LX_NoQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, OZ_NoQueryEventArgs LX_NoQueryEventArgs)
        {
            //API请求是否成功
            LX_NoQueryEventArgs.Success = LX_NoQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private async void InterfaceBusiness_BeforeQueryEvent(object sender, OZ_QueryEventArgs queryEventArgs)
        {
            try
            {
                //同一个seller_id授权的店铺任取一个sid请求报表数据即可
                //queryEventArgs.CustomData = sellerInterfaceBusiness.Query<Seller>(sellerInterfaceBusiness.LX_Query, SqlDb);
                //设置请求头参数
                var key = JObject.Parse(OZ_Query.TargetLoginData);
                Dictionary<string, string> headers = new Dictionary<string, string>();
                headers.Add("Client-Id", key["Client-Id"].Value<string>());
                headers.Add("Api-Key", key["Api-Key"].Value<string>());
                queryEventArgs.UrlQuery.Header = new Header() { Headers = headers };
                queryEventArgs.Page.PageSize = queryEventArgs.APINodes.Where(x => x.TargetField == "limit").First().SourceField.ToInt();
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, OZ_QueryEventArgs queryEventArgs)
        {
            //获取请求的数据
            OZ_ReqDTO data = new OZ_ReqDTO();
            data.cursor = queryEventArgs.Page.SidIndex_s;
            queryEventArgs.reqData = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, OZ_QueryEventArgs queryEventArgs)
        {

            try
            {
                //将查询后的数据转换成对应格式的数据
                ProductInfoStocksDTO result = (ProductInfoStocksDTO)JsonConvert.DeserializeObject<ProductInfoStocksDTO>(queryEventArgs.ResultStr);
                result.items.ForEach(x => {
                    x.stocks.ForEach(y =>
                    {
                        y.sellerId = queryEventArgs.UrlQuery.Header.Headers["Client-Id"];
                        y.msku = x.offer_id;
                        y.product_id = x.product_id;
                        y.id = y.msku + y.type + y.sellerId;
                    });
                });
                if (result.items.Count < queryEventArgs.Page.PageSize)
                {
                    queryEventArgs.Success = true;
                    queryEventArgs.Rows = result.items;
                    queryEventArgs.Page.SidIndex_s = result.cursor;
                    queryEventArgs.Page.Complete = true;
                }
                else
                {
                    queryEventArgs.Success = true;
                    queryEventArgs.Page.SidIndex_s = result.cursor;
                    queryEventArgs.Rows = result.items;
                }
            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {
            List<object> QQ = await this.QueryAsync<object>(this.OZ_Query, SqlDb);
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
